package playtools.wizard;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;

import playtools.PlayTools;
import playtools.core.PlayOperator;
import playtools.util.UIUtils;

public class NewProjectWizard extends Wizard implements INewWizard, IExecutableExtension {

	private PlayProjectConfiguration projectConfiguration;
	private NewProjectPage newProjectPage;
	private IConfigurationElement cfg;
	private IWorkbench workbench;
	public NewProjectWizard() {
		this.setWindowTitle("New Play Project");
		this.setNeedsProgressMonitor(true);
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.workbench = workbench;
		String o = PlayTools.checkPlayPath();
		if(o != null){ 
			MessageDialog.openError(UIUtils.getGlobalShell(), "错误",o.toString());
		}
	}
	
	public void addPages(){
		projectConfiguration = new PlayProjectConfiguration();
		this.newProjectPage = new NewProjectPage();
		this.addPage(newProjectPage);
	}

	@Override
	public boolean performFinish() {
		String result = this.newProjectPage.verify();
		if(result != null){
			MessageDialog.openError(UIUtils.getGlobalShell(), "错误", "存在以下错误" + result);
		    return false;
		}
		this.newProjectPage.setValues(this.projectConfiguration);
		
		//PlayOperator.INSTANCE.execute("new", this.projectConfiguration.getProjectName(), this.projectConfiguration.getAppName(), this.projectConfiguration.getLocation());
		
		//new NewProjectJob("新建任务").schedule();
		final String projName = this.projectConfiguration.getProjectName();
		final String location = this.projectConfiguration.getLocation();
		final String projLocation = location + File.separator + projName;
		IWorkspace workspace = PlayTools.getWorkspace();
		final IProject project = workspace.getRoot().getProject(projName);
		final String descPath = new File(projLocation + File.separator + ".project").getAbsolutePath();//.toURI();
		
		IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
			    public void run(IProgressMonitor monitor) throws CoreException {
			    	monitor.beginTask("创建play项目：" + projLocation, 16);
			    	monitor.subTask("执行 play new");
			    	Boolean result = (Boolean) PlayOperator.INSTANCE.execute("new", projName, projectConfiguration.getAppName(), location);
			    	monitor.worked(5);
			    	if(!result){
			    		throw new RuntimeException("执行play new 失败");
			    	}
			    	monitor.subTask("执行 play eclipsify");
					result = (Boolean) PlayOperator.INSTANCE.execute("eclipsify", projLocation);
					monitor.worked(5);	
					if(!result){
						throw new RuntimeException("执行play eclipsify 失败");
					}
					monitor.subTask("执行导入");
					importProject(project, descPath, new SubProgressMonitor(monitor, 5));
					monitor.worked(1);
					monitor.done();	
			    }
         };
         WizardProgressAdapter adapter = new WizardProgressAdapter(runnable, PlayTools.getResourceRuleFactory().createRule(project));
         try {
			this.getContainer().run(true, false, adapter);
		} catch (InvocationTargetException e) {
			MessageDialog.openError(UIUtils.getGlobalShell(), "Error", "创建项目失败，详情：" + e.getTargetException());
			return false;
		} catch (InterruptedException e) {
		}
        IWorkingSet[] workingSets= this.newProjectPage.getSelectedWorkingSets();
 		if (workingSets.length > 0) {
 			PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(project, workingSets);
 		}
         BasicNewProjectResourceWizard.updatePerspective(this.cfg);
		 BasicNewResourceWizard.selectAndReveal(project, workbench.getActiveWorkbenchWindow());
		return true;
	}
	
	private boolean importProject(IProject project,  String descPath, IProgressMonitor monitor){
		try {
		    IWorkspace workspace = PlayTools.getWorkspace();
		    IProjectDescription description = workspace.loadProjectDescription(new Path(descPath));//.newProjectDescription(project.getName());//
			project.create(description, new SubProgressMonitor(monitor, 2));
			project.open(new SubProgressMonitor(monitor, 3));
		} catch (CoreException e) {
			return false;
		}finally{
			 monitor.done();
		}
	    return true;
	}

	public void setInitializationData(IConfigurationElement config,
			String propertyName, Object data) throws CoreException {
		this.cfg = config;	
	}
}
